package com.qiangesoft.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qiangesoft.security.pojo.ResultVO;
import com.qiangesoft.security.service.CustomUserDetails;
import com.qiangesoft.security.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证成功处理器
 *
 * @author qiangesoft
 * @date 2024-05-14
 */
@Slf4j
@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        log.info("认证成功");

        // 生成token
        CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
        String jwt = jwtUtil.generateToken(userDetails.getUsername());
        // todo 缓存token

        // 返回结果
        response.setContentType("application/json;charset=utf-8");
        String string = new ObjectMapper().writeValueAsString(ResultVO.ok("认证成功", jwt));
        response.getWriter().write(string);
    }

}
